package com.example.kt_wear_app.presentation.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.Camera
import android.os.Environment
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object TakeCameraUtils {
    private var camera: Camera? = null
    private const val CAMERA_PERMISSION_REQUEST_CODE = 1

    fun startSilentCapture(context: Context) {
        if (ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            if (context is androidx.appcompat.app.AppCompatActivity) {
                ActivityCompat.requestPermissions(
                    context,
                    arrayOf(Manifest.permission.CAMERA),
                    CAMERA_PERMISSION_REQUEST_CODE
                )
            }
        } else {
            performSilentCapture(context)
        }
    }

    fun handlePermissionResult(
        context: Context,
        requestCode: Int,
        grantResults: IntArray
    ) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                performSilentCapture(context)
            } else {
                Toast.makeText(context, "相机权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun performSilentCapture(context: Context) {
        try {
            camera = Camera.open()
            val parameters = camera?.parameters
            parameters?.focusMode = Camera.Parameters.FOCUS_MODE_AUTO
            camera?.parameters = parameters

            val previewSize = parameters?.previewSize
            val surfaceTexture = android.graphics.SurfaceTexture(0)
            camera?.setPreviewTexture(surfaceTexture)
            camera?.startPreview()

            camera?.takePicture(null, null, PhotoHandler(context))
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "无法打开相机", Toast.LENGTH_SHORT).show()
        }
    }

    private class PhotoHandler(private val context: Context) : Camera.PictureCallback {
        override fun onPictureTaken(data: ByteArray?, camera: Camera?) {
            val pictureFile = getOutputMediaFile()
            if (pictureFile == null) {
                Toast.makeText(context, "无法创建文件来保存图片", Toast.LENGTH_SHORT).show()
                return
            }
            try {
                val fos = FileOutputStream(pictureFile)
                fos.write(data)
                fos.close()
                Toast.makeText(context, "照片已保存", Toast.LENGTH_SHORT).show()
            } catch (e: IOException) {
                e.printStackTrace()
                Toast.makeText(context, "保存照片时出错", Toast.LENGTH_SHORT).show()
            } finally {
                camera?.release()
            }
        }
    }

    private fun getOutputMediaFile(): File? {
        val mediaStorageDir =
            File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "SilentPhotoCapture"
            )
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null
            }
        }
        val timeStamp = System.currentTimeMillis().toString()
        return File("${mediaStorageDir.path}${File.separator}IMG_$timeStamp.jpg")
    }
}
